﻿var autocomplete;
var contextMenuForMarker;
var contextMenuForMap;
var markerList = [];
var markerCount = 0;
var selectedMarkerID;
var MARKER_ID = 'id';
var MARKER_ADDRESS = 'address';
var MARKER_CODE = 'code';
var MARKER_COMMAND = 'command';
var markerObjects = [];

var EMPTY = -1;
var NONE = 0;
var INSERT = 1;
var UPDATE = 2;
var DELETE = 3;

function compareLocation(location1, location2) {
    var distance = google.maps.geometry.spherical.computeDistanceBetween(location1, location2);
    if (distance <= 3) {
        return true;
    }
    return false;
}

function createMarker(location, title, address) {
    for (var i = 0; i < markerList.length; i++) {
        var marker = new google.maps.Marker(markerList[i]);
        if (compareLocation(marker.getPosition(), location)) {
            return;
        }
    }
    var marker
    marker = new google.maps.Marker({
        map: map,
        draggable: true,
        animation: google.maps.Animation.DROP,
        position: location,
        title: title,
        icon: 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=' + markerCount + '|FF776B|000000',
    });

    marker.set(MARKER_ID, markerCount);
    marker.set(MARKER_ADDRESS, address);
    marker.set(MARKER_COMMAND, INSERT);
    marker.set(MARKER_CODE, EMPTY);
    markerList.push(marker);
    markerCount += 1;
    selectedMarkerID = markerCount;
    var infowindow = new google.maps.InfoWindow({
        content: marker.title + "</br>" + marker.get(MARKER_ADDRESS)
    });

    google.maps.event.addListener(marker, 'dragend', function () {
        selectedMarkerID = marker.get(MARKER_ID);
        updateMarkerInfo(marker);
    });
    google.maps.event.addListener(marker, 'mouseout', function () {
        infowindow.close(map, marker);
    });
    google.maps.event.addListener(marker, 'click', function () {
        selectInList(marker.get(MARKER_ID));
        selectedMarkerID = marker.get(MARKER_ID);
        infowindow = new google.maps.InfoWindow({
            content: marker.title + "</br>" + marker.get(MARKER_ADDRESS)
        });
        infowindow.open(map, marker);
    });
    google.maps.event.addListener(marker, 'rightclick', function (mouseEvent) {
        selectedMarkerID = marker.get(MARKER_ID);
        contextMenuForMarker.show(mouseEvent.latLng);
    });
}
function createMarkerFromDatabase(location, title, address, Code) {
    for (var i = 0; i < markerList.length; i++) {
        var marker = new google.maps.Marker(markerList[i]);
        if (compareLocation(marker.getPosition(), location)) {
            return;
        }
    }
    var marker = new google.maps.Marker({
        map: map,
        draggable: true,
        animation: google.maps.Animation.DROP,
        position: location,
        title: title,
        icon: 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=' + markerCount + '|FF776B|000000',
    });

    marker.set(MARKER_ID, markerCount);
    marker.set(MARKER_ADDRESS, address);
    marker.set(MARKER_COMMAND, NONE);
    marker.set(MARKER_CODE, Code);
    markerList.push(marker);
    markerCount += 1;
    selectedMarkerID = markerCount;
    var infowindow = new google.maps.InfoWindow({
        content: marker.title + "</br>" + marker.get(MARKER_ADDRESS)
    });

    google.maps.event.addListener(marker, 'dragend', function () {
        selectedMarkerID = marker.get(MARKER_ID);
        updateMarkerInfo(marker);
    });
    google.maps.event.addListener(marker, 'mouseout', function () {
        infowindow.close(map, marker);
    });
    google.maps.event.addListener(marker, 'click', function () {
        selectInList(marker.get(MARKER_ID));
        selectedMarkerID = marker.get(MARKER_ID);
        infowindow = new google.maps.InfoWindow({
            content: marker.title + "</br>" + marker.get(MARKER_ADDRESS)
        });
        infowindow.open(map, marker);
    });
    google.maps.event.addListener(marker, 'rightclick', function (mouseEvent) {
        selectedMarkerID = marker.get(MARKER_ID);
        contextMenuForMarker.show(mouseEvent.latLng);
    });
    addMarkerToTable(marker);
}

function displayMarkerFromDatabase(location, title, address, Code) {
    var marker = new google.maps.Marker({
        map: map,
        animation: google.maps.Animation.DROP,
        position: location,
        title: title,
    });

    var infowindow = new google.maps.InfoWindow({
        content: marker.title + "</br>" + address
    });
    google.maps.event.addListener(marker, 'mouseout', function () {
        infowindow.close(map, marker);
    });
    google.maps.event.addListener(marker, 'click', function () {
        selectInList(marker.get(MARKER_ID));
        selectedMarkerID = marker.get(MARKER_ID);
        infowindow = new google.maps.InfoWindow({
            content: marker.title + "</br>" + address
        });
        infowindow.open(map, marker);
    });
}

function changeMarkerColor(id, selected) {
    for (var i = 0; i < markerList.length; i++) {
        if (markerList[i].get(MARKER_ID) == id) {
            if (selected) {
                markerList[i].setIcon('https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=' + id + '|0012ff|FFFFFF');
            } else {
                markerList[i].setIcon('https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=' + id + '|FF776B|000000');
            }
            updateDivInfo(markerList[i]);
            break;
        }
    }
}
function updateMarkerInfo(marker) {
    var marker = new google.maps.Marker(marker);
    geocoder.geocode({ 'latLng': marker.getPosition(), 'region': 'vi' }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var title = marker.title;
            var address = results[0].formatted_address;
            for (var i = 0; i < markerList.length; i++) {
                if (markerList[i].get(MARKER_ID) == marker.get(MARKER_ID)) {
                    markerList[i].setPosition(results[0].geometry.location);
                    markerList[i].setTitle(title);
                    markerList[i].set(MARKER_ADDRESS, address);
                    updateDivInfo(markerList[i]);
                    break;
                }
            }
            
            for (var i = 0; i < markerObjects.length; i++) {
                if (markerObjects[i].ID == marker.get(MARKER_ID)) {
                    markerObjects[i].Longitude = results[0].geometry.location.lng();
                    markerObjects[i].Latitude = results[0].geometry.location.lat();
                    markerObjects[i].Name = title;
                    markerObjects[i].Address = address;
                    markerObjects[i].Command = UPDATE;
                    break;
                }
            }
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
}

function removeMarker(markerID) {
    var index = -1;
    for (var i = 0; i < markerList.length; i++) {
        var marker = new google.maps.Marker(markerList[i]);
        if (marker.get(MARKER_ID) == markerID) {
            marker.setMap(null);
            marker.setVisible(false);
            selectedMarkerID = -1;
            index = i;
            break;
        }
    }
    markerList.splice(index, 1);
    for (var i = 0; i < markerObjects.length; i++) {
        if (markerObjects[i].ID == marker.get(MARKER_ID)) {
            markerObjects[i].Command = DELETE;
            break;
        }
    }
}

function selectMarker(markerID) {
    for (var i = 0; i < markerList.length; i++) {
        var marker = new google.maps.Marker(markerList[i]);
        if (marker.get(MARKER_ID) == markerID) {
            return marker;
        }
    }
    return null;
}

function removeAllMarker() {
    for (var i = 0; i < markerList.length; i++) {
        var marker = new google.maps.Marker(markerList[i]);
        marker.setMap(null);
        marker.setVisible(false);
    }
    markerList = [];
    document.getElementById('div_marker').innerHTML = "";
}

function codeAddress() {
    var keyword = document.getElementById('searchTextField').value;
    geocoder.geocode({ 'address': keyword }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var full_address = results[0].formatted_address;
            var n = full_address.indexOf(",");
            var title = full_address.substring(0, n);
            var address = full_address.substring(n + 1);
            map.setCenter(results[0].geometry.location);
            createMarker(results[0].geometry.location, title, address);
        } else {
            alert('Chúng tôi không thể lấy thông tin ở vị trí này');
        }
    });
}

function getAddress(latLng) {
    geocoder.geocode({ 'latLng': latLng }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var full_address = results[0].formatted_address;
            var title = prompt("Vui lòng nhập tên cửa hàng này", null)
            if (title != null) {
                createMarker(results[0].geometry.location, title, full_address);
            }
        } else {
            alert('Chúng tôi không thể lấy thông tin ở vị trí này');
        }
    });
}

function initAutocomplete() {
    var input = document.getElementById('searchTextField');
    var options = {
        types: ['(cities)'],
        componentRestrictions: { country: 'vn' }
    };
    autocomplete = new google.maps.places.Autocomplete(input, options);
    autocomplete.bindTo('bounds', map);

    google.maps.event.addListener(autocomplete, 'place_changed', function () {
        var place = autocomplete.getPlace();
        if (!place.geometry) {
            input.className = 'notfound';
            return;
        }
        if (place.geometry.viewport) {
            map.fitBounds(place.geometry.viewport);
        } else {
            map.setCenter(place.geometry.location);
            map.setZoom(17);
        }
        createMarker(place.geometry.location, place.name, place.formatted_address);
    });
}


// Context Menu ------------------------------------------------------------------------------------
function createContextMenuForMarker() {
    var contextMenuOptions = {};
    contextMenuOptions.classNames = { menu: 'context_menu', menuSeparator: 'context_menu_separator' };
    var menuItems = [];
    menuItems.push({ className: 'context_menu_item', eventName: 'add', label: 'Thêm vào danh sách' });
    menuItems.push({});
    menuItems.push({ className: 'context_menu_item', eventName: 'update', label: 'Đổi tên' });
    menuItems.push({});
    menuItems.push({ className: 'context_menu_item', eventName: 'remove', label: 'Xóa điểm này' });
    contextMenuOptions.menuItems = menuItems;
    contextMenuForMarker = new ContextMenu(map, contextMenuOptions);

    google.maps.event.addListener(contextMenuForMarker, 'menu_item_selected', function (latLng, eventName) {
        switch (eventName) {
            case 'add':
                var marker = selectMarker(selectedMarkerID);
                addMarkerToTable(marker);
                break;
            case 'remove':
                removeDivInfo(selectedMarkerID);
                removeMarker(selectedMarkerID);
                break;
            case 'update':
                var marker = selectMarker(selectedMarkerID);
                var title = prompt("Vui lòng nhập tên cửa hàng này", null)
                marker.title = title;
                updateMarkerInfo(marker);
                break;
        }
    });
}

function addMarkerToTable(marker) {
    if (marker != null) {
        var divID = 'p' + marker.get(MARKER_ID);
        var divInfo = document.getElementById(divID)
        if (divInfo == null) {
            markerObjects.push(createMakerObject(marker));
            document.getElementById('div_marker').innerHTML += showMarkerInfo(marker);
        } else {
            alert("Vị trí này đã có trong danh sách của bạn rồi.");
        }
    }
}

function createContextMenuForMap() {
    var contextMenuOptions = {};
    contextMenuOptions.classNames = { menu: 'context_menu', menuSeparator: 'context_menu_separator' };
    var menuItems = [];
    menuItems.push({ className: 'context_menu_item', eventName: 'add_here', label: 'Đặt vị trí tại đây' });
    menuItems.push({});
    menuItems.push({ className: 'context_menu_item', eventName: 'remove_all', label: 'Xóa tất cả vị trí' });
    contextMenuOptions.menuItems = menuItems;
    contextMenuForMap = new ContextMenu(map, contextMenuOptions);

    google.maps.event.addListener(contextMenuForMap, 'menu_item_selected', function (latLng, eventName) {
        switch (eventName) {
            case 'add_here':
                getAddress(latLng);
                break;
            case 'remove_all':
                if (markerList.length > 0) {
                    if (confirm("Bạn có chắc là xóa hết những điểm đã đánh dấu trên bản đồ không?")) {
                        removeAllMarker();
                    }
                }
                break;
        }
    });
    google.maps.event.addListener(map, 'rightclick', function (mouseEvent) {
        contextMenuForMap.show(mouseEvent.latLng);
    });
}
// -----------------------------------------------------------------------------------------------------

function createMakerObject(marker) {
    var markerObj = new Object();
    markerObj.ID = marker.get(MARKER_ID);
    markerObj.Name = marker.title;
    markerObj.Address = marker.get(MARKER_ADDRESS);
    markerObj.Longitude = marker.getPosition().lng();
    markerObj.Latitude = marker.getPosition().lat();
    markerObj.Code = marker.get(MARKER_CODE);
    markerObj.Command = marker.get(MARKER_COMMAND);
    return markerObj;
}



function panToMarker(id) {
    var marker = selectMarker(id);
    map.setCenter(marker.getPosition());
    selectInList(id);
}

function selectInList(id) {
    var oldDivInfo = document.getElementById('p' + selectedMarkerID);
    var selectedDivInfo = document.getElementById('p' + id);
    if (oldDivInfo != null && selectedDivInfo != null) {
        oldDivInfo.style.backgroundColor = '#FFFFFF';
        changeMarkerColor(selectedMarkerID, false);
        selectedDivInfo.style.backgroundColor = '#f4f3f0';
        changeMarkerColor(id, true);
        selectedMarkerID = id;
    }
}

function removeDivInfo(id) {
    var selectedDivInfo = document.getElementById('p' + id);
    if (selectedDivInfo != null) {
        selectedDivInfo.parentNode.removeChild(selectedDivInfo);
    }
}

function getMarkerImageUrl(id) {
    return 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=' + id + '|FF776B|000000'
}
function showMarkerInfo(marker) {

    var html = '<a onclick="panToMarker(' + marker.get(MARKER_ID) + ')">';
    html += '<div class="info" id="p' + marker.get(MARKER_ID) + '">';
    html += '<table><tr valign="top">';
    html += '<td style="padding: 2px"><img src="' + getMarkerImageUrl(marker.get(MARKER_ID)) + '"/></td>';
    html += '<td style="padding: 2px">' + getMarkerDescription(marker) + '</td>';
    html += '</tr></table>';
    html += '</div></a>';
    return html;
}
function changeMarkerInfo(marker) {
    var html = '<table><tr valign="top">';
    html += '<td style="padding: 2px"><img src="' + getMarkerImageUrl(marker.get(MARKER_ID)) + '"/></td>';
    html += '<td style="padding: 2px">' + getMarkerDescription(marker) + '</td>';
    html += '</tr></table>';
    return html;
}
function getMarkerDescription(marker) {
    var html = '<table class="tabContent">';
    html += tr('Tên', marker.title);
    html += tr('Địa chỉ', marker.get(MARKER_ADDRESS));
    html += tr('Longitude', marker.getPosition().lng());
    html += tr('Latitude', marker.getPosition().lat());
    html += '</table>';
    return html;
}

function tr(key, value) {
    return '<tr>' +
             '<td class="key">' + key + (key ? ':' : '') + '</td>' +
             '<td class="value">' + value + '</td>' +
           '</tr>';
}

function updateDivInfo(marker) {
    var divID = 'p' + marker.get(MARKER_ID);
    var divInfo = document.getElementById(divID);
    if (divInfo != null) {
        divInfo.innerHTML = changeMarkerInfo(marker);
    }
}

function saveMarkerJobect() {
    document.getElementById('markerObjects').value = JSON.stringify(markerObjects);
}
var MyJson;
function displayMarkers() {
    markerList = [];
    if (MyJson.length > 1) {
        for (var i = 0; i < MyJson.length; i++) {
            var Name = MyJson[i].Name;
            var Address = MyJson[i].Address;
            var LatLng = new google.maps.LatLng(MyJson[i].Latitude, MyJson[i].Longitude);
            var code = MyJson[i].Code;
            createMarkerFromDatabase(LatLng, Name, Address, code);
        }
    } else if(MyJson.length==1) {
        var Name = MyJson[0].Name;
        var Address = MyJson[0].Address;
        var LatLng = new google.maps.LatLng(MyJson[0].Latitude, MyJson[0].Longitude);
        map.setCenter(LatLng);
        var code = MyJson[0].Code;
        createMarkerFromDatabase(LatLng, Name, Address, code);
    }
    MyJson = null;
}

function displayOneMarker() {
    if (MyJson.length > 0) {
        for (var i = 0; i < MyJson.length; i++) {
            var Name = MyJson[i].Name;
            var Address = MyJson[i].Address;
            var LatLng = new google.maps.LatLng(MyJson[i].Latitude, MyJson[i].Longitude);
            map.setCenter(LatLng);
            var code = MyJson[i].Code;
            displayMarkerFromDatabase(LatLng, Name, Address, code);
        }
    }
    MyJson = null;
}

function setMarkerFromDatabase(json) {
    MyJson = JSON.parse(json);
}
